﻿using System;
using System.Collections.Generic;
using System.Text;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;
using System.Net;
using System.IO;
using Top.Api.Util;

namespace 合并页面
{
    public class TaoBaoApi
    {
        string m_appKey;
        string m_appSecret;
        string m_sessionKey;
        ITopClient m_client;

        public string AppKey
        {
            get { return this.m_appKey; }
            set { m_appKey = value; }
        }

        public string AppSecret {
            get { return this.m_appSecret; }
            set { m_appSecret = value; }
        }

        public string SessionKey {
            get { return this.m_sessionKey; }
            set { m_sessionKey = value; }
        }

        public TaoBaoApi() { }

        public TaoBaoApi(string nickName)
        {
            this.m_appKey = IniFile.GetKeyValue(nickName, "appKey", "sys.ini");
            this.m_appSecret = IniFile.GetKeyValue(nickName, "appSecret", "sys.ini");
            this.m_sessionKey = IniFile.GetKeyValue(nickName, "sessionKey", "sys.ini");
            this.m_client = new DefaultTopClient("http://gw.api.taobao.com/router/rest", m_appKey, m_appSecret);
        }

        /// <summary>
        /// 得到图片的链接。
        /// </summary>
        /// <param name="imgName">图片名称</param>
        /// <param name="directory">图片所属的文件夹</param>
        /// <returns>返回为""或者返回图片链接</returns>
        public string GetImageLink(string directory,string imgName)
        {   
            //图片分类信息
            PictureCategoryGetRequest imgCatReq = new PictureCategoryGetRequest();
            imgCatReq.PictureCategoryName = directory;//文件夹名
            PictureCategoryGetResponse imgCatRes = m_client.Execute(imgCatReq, m_sessionKey);

            if (imgCatRes.IsError== false)
            {
                if(imgCatRes.PictureCategories.Count==0)
                    System.Windows.Forms.MessageBox.Show("图片空间没有该文件夹");
                else if (imgCatRes.PictureCategories.Count == 1)
                {
                    //图片信息
                    PictureGetRequest imgReq = new PictureGetRequest();
                    imgReq.PictureCategoryId = imgCatRes.PictureCategories[0].PictureCategoryId;// .PictureCategoryId;
                    imgReq.Title = imgName.Split('.')[0];
                    PictureGetResponse imgRes = m_client.Execute(imgReq, m_sessionKey);
                    if (imgRes.TotalResults == 0)
                        return "";
                    else 
                        return imgRes.Pictures[0].PicturePath;
                } 
                else
                    System.Windows.Forms.MessageBox.Show("图片空间有重复的文件夹");

            }
            else
            {
                System.Windows.Forms.MessageBox.Show("请检查Session是否正确或 "+directory+" 文件是否存在");
            }
            return "";
        }

        /// <summary>
        /// 判断分类是否存在。
        /// </summary>
        /// <param name="fileName">图片分类文件夹</param>
        /// <returns>存在返回 true  不存在返回 false</returns>
        public bool CatFileExist(string fileName)
        {
            PictureCategoryGetRequest imgCatReq = new PictureCategoryGetRequest();
            PictureCategoryGetResponse imgCatRes = m_client.Execute(imgCatReq, m_sessionKey);
            for (int i = 0; i < imgCatRes.PictureCategories.Count; i++)
            {
                if (fileName == imgCatRes.PictureCategories[i].PictureCategoryName)
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 根据分类名称得到分类ID
        /// </summary>
        /// <param name="fileCatName"></param>
        /// <returns></returns>
        private long GetCatID(string fileCatName)
        {
            PictureCategoryGetRequest imgCatReq = new PictureCategoryGetRequest();
            PictureCategoryGetResponse imgCatRes = m_client.Execute(imgCatReq, m_sessionKey);
            for (int i = 0; i < imgCatRes.PictureCategories.Count; i++)
            {
                if (imgCatRes.PictureCategories[i].PictureCategoryName == fileCatName)
                    return imgCatRes.PictureCategories[i].PictureCategoryId;
            }
            return 0L;
        }

        private long GetImageID(string fileCat, string imgName)
        {
            long catID = GetCatID(fileCat);
            PictureGetRequest imgReq = new PictureGetRequest();
            imgReq.PictureCategoryId = catID;// .PictureCategoryId;
            imgReq.Title = imgName.Split('.')[0];
            PictureGetResponse imgRes = m_client.Execute(imgReq, m_sessionKey);
            return imgRes.Pictures[0].PictureId;
        }


        public long CreateCatFile(string fileName)
        {
            PictureCategoryAddRequest req = new PictureCategoryAddRequest();
            req.PictureCategoryName = fileName;
            req.ParentId = 0L;
            PictureCategoryAddResponse response = m_client.Execute(req, m_sessionKey);
            return response.PictureCategory.PictureCategoryId;
            //return 1;
        }

        /// <summary>
        /// 判断图片是否存在
        /// </summary>
        /// <param name="fileCat"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        private bool Contains(string fileCat, string title)
        {
            PictureGetRequest req = new PictureGetRequest();
            req.PictureCategoryId = GetCatID(fileCat);
            req.Title = title.Split('.')[0];
            PictureGetResponse res = m_client.Execute(req, m_sessionKey);
            if (res.Pictures.Count == 0)
                return false;
            else 
                return true;
        }

        /// <summary>
        /// 将图片list中的图片上传到空间中。如果图片分类中有该图片则进行替换。不存在就上传
        /// </summary>
        /// <param name="list">图片list</param>
        /// <param name="fileCat">图片要放入到的文件类别</param>
        /// <returns></returns>
        public int UploadImage(string fileCatName,string title,string localpath)
        {
            long catID = GetCatID(fileCatName);
            if (catID == 0L)
            {
                catID=CreateCatFile(fileCatName);
            }
            if (!Contains(fileCatName, title))
            {
                PictureUploadRequest req = new PictureUploadRequest();
                req.PictureCategoryId = catID;
                FileItem fItem = new FileItem(localpath);
                req.Img = fItem;
                req.ImageInputTitle = title.Split('.')[0];
                req.Title = title.Split('.')[0];
                PictureUploadResponse response = m_client.Execute(req, m_sessionKey);
            }
            return 1;
        }

        public int ReplaceImage(string fileCatName, string title, string localpath)
        {

            PictureReplaceRequest req = new PictureReplaceRequest();
            req.PictureId = GetImageID(fileCatName, title);
            FileItem fItem = new FileItem(localpath);
            req.ImageData = fItem;
            PictureReplaceResponse res = m_client.Execute(req, m_sessionKey);
            return 1;
        }
    }
}
